package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.SaleCartBean;
import com.project.mapper.ISaleCartMapper;
import com.project.service.ISaleCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SaleCartServiceImpl implements ISaleCartService {
    @Autowired
    private ISaleCartMapper cartMapper;

    @Override
    public List<SaleCartBean> findByUserId(Integer userId) {
        return cartMapper.findByUserId(userId);
    }

    @Override
    public void del(Integer id) {
        cartMapper.deleteById(id);
    }

    @Override
    public void add(SaleCartBean saleCart) {
        QueryWrapper<SaleCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", saleCart.getUserId());
        qw.eq("fk_productId", saleCart.getProductId());
        SaleCartBean oldSaleCart = cartMapper.selectOne(qw);
        if (oldSaleCart != null) {
            oldSaleCart.setNum(oldSaleCart.getNum() + 1);
            cartMapper.updateById(oldSaleCart);
        } else {
            cartMapper.insert(saleCart);
        }

    }

    @Override
    public void update(Integer id, Integer num) {
        SaleCartBean saleCart = cartMapper.selectById(id);
        saleCart.setNum(num);
        cartMapper.updateById(saleCart);

    }
}
